// ==UserScript==
// @name         问题详情页改造
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.zhihu.com/question/*
// @grant        unsafeWindow
// @run-at       document-start
// ==/UserScript==

; (function () {
  'use strict'
  //https://www.zhihu.com/api/v4/questions/338688699/answers
  const fetch = unsafeWindow.fetch
  const console = unsafeWindow.console
  const pluginName = '问题详情页改造'
  function log(...data) {
    console.log(pluginName, ...data)
  }
  const oneDay = 24 * 60 * 60 * 1000
  const oneYear = 365 * oneDay
  const oneSeason = 90 * oneDay
  const now = Date.now()
  function $(selector, doc = document) {
    return doc.querySelectorAll(selector)
  }
  function makeDateTitleTip(date) {
    let gap = now - date
    let color = '#666'
    if (gap > oneYear) {
      color = '#CC0000'
    } else if (gap > oneSeason) {
      color = '#CC00FF'
    }
    let dateStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    let dateTitleStr = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
    return `<span style="color:${color}" title='${dateTitleStr}'>${dateStr}</span><br>`
    // return [dateTitleStr, dateStr]
  }
  window.addEventListener('load', _ => {
    setTimeout(() => {
      $('.List-item').forEach(item => {
        if ($('.KfeCollection-PaidAnswerFooter', item).length > 0) {
          item.remove()
        }
        let timeEl = $('[itemprop=dateModified]', item)[0]
        if (timeEl) {
          let time = timeEl.getAttribute('content')
          let date = new Date(time)
          let tip = makeDateTitleTip(date)
          $('.RichContent-inner', item).forEach(content => {
            let span = document.createElement('span')
            span.innerHTML = tip
            content.prepend(span.children[0])
          })
        }
      })
      $('#js-initialData').forEach(item => {
        let json = JSON.parse(item.innerHTML)
        let answers = json.initialState.entities.answers
        Object.entries(answers).forEach(([key, value]) => {
          let updatedTime = value.updatedTime
          updatedTime = updatedTime * 1000
          let date = new Date(updatedTime)
          value.content = makeDateTitleTip(date) + value.content
        })
        item.innerHTML = JSON.stringify(json, null, 2)
      })
    }, 0)
  })
  unsafeWindow.fetch = function wrappedFetch(...args) {
    return fetch(...args).then(response => {
      if (/https:\/\/www.zhihu.com\/api\/v4\/questions\/.+\/feeds/.test(response.url)) {
        return response.json().then(body => {
          response.json = function wrappedJson() {
            try {
              let { data } = body
              let filteredData = []
              filteredData = data.filter(item => item.target.answer_type != 'paid')
              if (data.length != filteredData.length) {
                log(
                  '删除了一些付费结果',
                  data.filter(item => item.target.answer_type == 'paid'),
                )
              }

              function addTip(item, tip) {
                if (item.content) {
                  item.content = tip + item.content
                }
                if (item.excerpt) {
                  item.excerpt = tip + item.excerpt
                }
                if (item.excerpt_new) {
                  item.excerpt_new = tip + item.excerpt_new
                }
              }
              filteredData.forEach(item => {
                // 开始改造内容
                let updateDate = item.target.updated_time
                if (!updateDate) {
                  updateDate = item.updated
                }

                if (updateDate) {
                  updateDate = updateDate * 1000
                  let date = new Date(updateDate)
                  let tip = makeDateTitleTip(date)
                  addTip(item.target, tip)
                } else {
                  log(`这里有个数据找不到时间`, item)
                }
                let voteup_count = item.target.voteup_count
                let comment_count = item.target.comment_count
                if (comment_count !== undefined && voteup_count !== undefined) {
                  if (comment_count / voteup_count > 2) {
                    let tip = '<span style="color:#999"> 这一条回答大概完全没有营养，可以忽略掉</span>'
                    addTip(item.target, tip)
                  }
                }
              })
              body.data = filteredData
              return Promise.resolve(body)
            } catch (e) {
              console.error(`${pluginName} -- 解析数据出错了`, e)
              return Promise.resolve(body)
            }
          }
          return response
        })
      }
      return response
    })
  }

  // Your code here...
})()
